<template>
  <div class="add-user-info">
    <div class="success-info">
      <div>
        <!-- <Icon type="md-checkmark-circle" size="26" color="#36b447" /> -->
        <span>{{$t('module.userManage.preInformation')}}</span>
      </div>
    </div>
    <div class="info-title">
      <!-- 尊敬的用户，请完善您的个人资料。 -->
      {{$t('module.userManage.preInforTip')}}
    </div>
    <div style="margin: 10px auto; width: 500px;">
      <Form
        :model="modelForm"
        ref="editForm"
        class="ivu-form-no-margin-bottom"
        :rules="rule"
        :label-width="0"
      >
        <Row :gutter="32" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item prop="userName">
              <Input
                v-model="modelForm.userName"
                prefix="ios-contact"
                :placeholder="$t('module.userManage.userName')"
                size="large"
                :maxlength="50"
              />
            </Form-item>
          </Col>
        </Row>
        <!-- <FormItem prop="captcha">
          <Input
            v-model="modelForm.captcha"
            prefix="md-key"
            placeholder="验证码"
            size="large"
            style="width:295px"
            :maxlength="10"
        />-->
        <!-- 验证码 -->
        <!-- <div style="display: inline-block;vertical-align: top;" @click="generateCaptchaUrl">
            <img :src="captchaUrl" />
          </div>
        </FormItem>-->
        <Row :gutter="32" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item prop="mobile">
              <Input
                v-model="modelForm.mobile"
                prefix="ios-phone-portrait"
                :placeholder="$t('module.userManage.cellPhoneNumber')"
                size="large"
                :maxlength="11"
              />
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="32" class="code-row-bg">
          <Col span="18" style="border:none;">
            <FormItem prop="mobileVerificationCode">
              <Input
                v-model="modelForm.mobileVerificationCode"
                prefix="md-text"
                :placeholder="$t('module.userManage.messageCode')"
                size="large"
                style="width:100%"
                :maxlength="10"
              />
            </FormItem>
          </Col>
          <Col span="6" style="border:none;">
            <RPButton
              size="large"
              style="width:100%; height:36px;"
              @click="getSMSCaptcha"
              :disabled="isWaitingForSMS || modelForm.mobile == ''"
              :text="getSMSButton"
            />
          </Col>
        </Row>
        <Row :gutter="32" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item prop="email">
              <Input
                v-model="modelForm.email"
                prefix="ios-mail"
                :placeholder="$t('module.userManage.email')"
                size="large"
                :maxlength="50"
              />
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="32" class="code-row-bg">
          <Col span="18" style="border:none;">
            <FormItem prop="mailVerificationCode">
              <Input
                v-model="modelForm.mailVerificationCode"
                prefix="md-text"
                :placeholder="$t('module.userManage.emailCode')"
                size="large"
                style="width:100%"
                :maxlength="10"
              />
            </FormItem>
          </Col>
          <Col span="6" style="border:none;">
            <RPButton
              size="large"
              style="width:100%; height:36px;"
              @click="getEmailCaptcha"
              :disabled="isWaitingForEmail || modelForm.email == ''"
              :text="getEmailButton"
            />
          </Col>
        </Row>
        <Row :gutter="32" class="code-row-bg">
          <Col span="12" style="border:none;">
            <FormItem>
              <RPButton
                optType="confirm"
                size="large"
                style="width:100%"
                @click="save"
                v-show="ifShowButton"
                :text="$t('common.submit')"
              />
            </FormItem>
          </Col>
          <Col span="12" style="border:none;">
            <FormItem>
              <RPButton
                optType="cancel"
                size="large"
                style="width:100%"
                @click="back"
                v-show="ifShowButton"
                :text="$t('common.back')"
              />
            </FormItem>
          </Col>
        </Row>
      </Form>
    </div>
  </div>
</template>
<script>
import locales from "./locales.js";
import {
  verificationWaittingTime,
  verificationTypeSMS,
  verificationTypeEmail,
  verificationSubTypeAddUserInfo
} from "@/const.js";
export default {
  name: "add-user-info",
  components: {},
  props: {},
  mixins: [locales],
  data() {
    const validateMobile = (rule, value, callback) => {
      if (value === "") {
        if (this.modelForm.email === "") {
          callback(new Error(this.$t("module.userManage.warning.enterCellPhoneNumber")));
        } else {
          callback();
        }
      } else if (!new RegExp("^1\\d{10}$").test(value)) {
        callback(new Error(this.$t("module.userManage.warning.enterCorrectTel")));
      }
      callback();
    };
    const validateMobileVerificationCode = (rule, value, callback) => {
      if (value === "") {
        if (this.modelForm.email === "") {
          callback(new Error(this.$t("module.userManage.warning.enterMessageCode")));
        } else {
          callback();
        }
      } else if (!new RegExp("\\d{6}$").test(value)) {
        callback(new Error(this.$t("module.userManage.warning.messageCodeTip")));
      }
      callback();
    };
    const validateEmail = (rule, value, callback) => {
      if (value === "") {
        if (this.modelForm.mobile === "") {
          callback(new Error(this.$t("module.userManage.warning.enterEmail")));
        } else {
          callback();
        }
      } else if (!new RegExp("^(\\w)+(\\.\\w+|-\\w+)*@(\\w)+((\\.\\w+)+)$").test(value)) {
        callback(new Error(this.$t(this.$t("module.userManage.warning.errorEmail"))));
      }
      callback();
    };
    const validateMailVerificationCode = (rule, value, callback) => {
      if (value === "") {
        if (this.modelForm.mobile === "") {
          callback(new Error(this.$t("module.userManage.warning.enterEmailCode")));
        } else {
          callback();
        }
      } else if (!new RegExp("\\d{6}$").test(value)) {
        callback(new Error(this.$t("module.userManage.warning.messageCodeTip")));
      }
      callback();
    };
    return {
      modelForm: {
        userName: "",
        captcha: "null",
        mobile: "",
        mobileVerificationCode: "",
        email: "",
        mailVerificationCode: ""
      },
      rule: {
        mobile: [
          {
            required: true,
            validator: validateMobile,
            trigger: "blur"
          }
        ],
        captcha: [
          {
            required: true,
            message: this.$t("module.userManage.warning.enterCode"),
            trigger: "blur"
          }
        ],
        mobileVerificationCode: [
          {
            required: true,
            validator: validateMobileVerificationCode,
            trigger: "blur"
          }
        ],
        userName: [
          {
            required: true,
            message: this.$t("module.userManage.warning.enter") + this.$t("module.userManage.userName"),
            trigger: "blur"
          }
        ],
        email: [
          {
            required: true,
            validator: validateEmail,
            trigger: "blur"
          }
        ],
        mailVerificationCode: [
          {
            required: true,
            validator: validateMailVerificationCode,
            trigger: "blur"
          }
        ]
      },
      captchaUrl: "",
      objParams: {},
      ifShowButton: true,
      getSMSButton: this.$t("module.userManage.getCode"),
      isWaitingForSMS: false,
      getEmailButton: this.$t("module.userManage.getCode"),
      isWaitingForEmail: false
    };
  },
  computed: {},
  created: function() {
    this.init();
  },
  beforeMount: function() {},
  mounted: function() {
    this.generateCaptchaUrl();
  },
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    init() {
      let indexOfParam = window.location.href.indexOf("?");
      if (indexOfParam == -1) return;
      let strParam = window.location.href.substr(indexOfParam + 1);
      let params = strParam.split("&");
      for (var i = 0; i < params.length; i++) {
        this.objParams[params[i].split("=")[0]] = unescape(params[i].split("=")[1]);
      }
      this.modelForm.accountType = this.objParams.accountType;
      this.modelForm.loginName = this.objParams.loginAccount;
    },
    generateCaptchaUrl() {
      this.captchaUrl = `${window.RPConfig.userCenter}/captcha?${Math.random()}`;
    },
    getSMSCaptcha() {
      this.$refs["editForm"].validateField("mobile", valid => {
        if (valid) {
          this.$message.error({
            content: valid,
            duration: 3
          });
        } else {
          this.isWaitingForSMS = true;
          this.getSMSButton = this.$t("module.userManage.sending");
          let param = {
            type: verificationTypeSMS,
            subType: verificationSubTypeAddUserInfo,
            recipient: this.modelForm.mobile
          };
          window.$http.post(`${window.RPConfig.userCenter}/message/send`, param).then(response => {
            let i = verificationWaittingTime;
            let intervalId = setInterval(() => {
              this.getSMSButton = this.$t("module.userManage.regain") + i-- + "s)";
              if (i == 0) {
                clearInterval(intervalId);
                this.isWaitingForSMS = false;
                this.getSMSButton = this.$t("module.userManage.regainCode");
              }
            }, 1000);

            this.$message.success({
              content: this.$t("module.userManage.sendSuccess"),
              duration: 3
            });
          });
        }
      });
    },
    getEmailCaptcha() {
      this.$refs["editForm"].validateField("email", valid => {
        if (valid) {
          this.$message.error({
            content: valid,
            duration: 3
          });
        } else {
          this.isWaitingForEmail = true;
          this.getEmailButton = this.$t("module.userManage.sending");
          let param = {
            type: verificationTypeEmail,
            subType: verificationSubTypeAddUserInfo,
            recipient: this.modelForm.email
          };
          window.$http.post(`${window.RPConfig.userCenter}/message/send`, param).then(response => {
            let i = verificationWaittingTime;
            let intervalId = setInterval(() => {
              this.getEmailButton = this.$t("module.userManage.regain") + i-- + "s)";
              if (i == 0) {
                clearInterval(intervalId);
                this.isWaitingForEmail = false;
                this.getEmailButton =  this.$t("module.userManage.regainCode");
              }
            }, 1000);

            this.$message.success({
              content: this.$t("module.userManage.sendSuccess"),
              duration: 3
            });
          });
        }
      });
    },
    save() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          window.$http
            .post(`${window.RPConfig.userCenter}/user/perfectInformation`, this.modelForm, null, {
              withCredentials: true
            })
            .then(response => {
              if (response.data.message) {
                this.$message.error({
                  content: response.data.message,
                  duration: 3
                });
              } else {
                this.$message.success({
                  // content: this.$t("common.createSuccess"),
                  content: this.$t("module.userManage.enterSystem"),
                  duration: 10,
                  closable: true,
                  onClose: () => {
                    this.goIntoSystem();
                  }
                });
                this.ifShowButton = false;
                this.isWaitingForEmail = true;
                this.isWaitingForSMS = true;
              }
            });
        }
      });
    },
    goIntoSystem() {
      if (this.$route.query && this.$route.query.service) {
        // 有参数service时
        if (window.location.href.indexOf(this.$route.query.service) == 0) {
          // 参数service为当前系统时
          window.location.href = "/";
        } else {
          // 参数service为外部系统时
          window.location.href = this.$route.query.service;
        }
      } else {
        // 无参数service时
        window.location.href = "/";
      }
    },
    back() {
      if (this.$route.query && this.$route.query.service) {
        // 有参数service时
        window.location.href = `${window.RPConfig.cas_logout}?service=` + this.$route.query.service;
      } else {
        // 无参数service时
        let domain = "http://" + window.location.host;
        window.location.href = `${window.RPConfig.cas_logout}?service=` + domain;
      }
    }
  },
  watch: {},
  directives: {}
};
</script>
<style lang="less">
.add-user-info {
  .success-info {
    width: 100%;
    height: 48px;
    display: table;
    text-align: center;

    div {
      display: table-cell;
      vertical-align: middle;
      span {
        font-size: 18px;
        font-weight: bold;
        color: #36b447;
        display: inline-block;
        vertical-align: middle;
      }
    }
  }
  .info-title {
    font-size: 14px;
    font-weight: bold;
    text-align: center;
  }
}
</style>
